import React from 'react';
import {Select , Spin} from 'antd';
import debounce from 'lodash.debounce';
import 'whatwg-fetch'

/**
 * 搜索框
 */
class SearchInput extends React.Component {
    constructor(props){
        super(props);
        this.onSearch = debounce(this.onSearch, this.props.delay || 800);
    }
  state = {
    data: [],
    value: '',
  }
  onSearch = (value) => {
    this.setState({ value });
    this.fetchData(value);
  }

  onSelect = (value) => {
      this.setState({ value })
  }

  fetchData = (keyword) => {
    let currentValue = keyword;
    let self = this;
    const url = this.getRequestUrl(keyword);
    fetch(url)
      .then(response => response.json())
      .then((resp) => {
        if (currentValue === keyword) {
            let data = this.handleResponse(resp);
            this.setState({data});
        }
      });
  }

  render() {
    const options = this.state.data.map(d => <Select.Option key={d.value}>{d.text}</Select.Option>);
    return (
      <Select
        mode="combobox"
        value={this.state.value}
        placeholder={this.props.placeholder}
        notFoundContent=""
        style={this.props.style}
        defaultActiveFirstOption={false}
        showArrow={false}
        filterOption={false}
        optionLabelProp="children"
        onSearch={this.onSearch}
        onSelect={this.onSelect}
      >
        {options}
      </Select>
    );
  }
}

export default SearchInput;